import React, {Component} from 'react';

import { connect } from 'dva';
import classnames from 'classnames';
import { bindActionCreators } from 'redux';
import widgetsActions from '../../../actions/Editor/widgets';
import UsedWidget from './UsedWidget';
import tool from '../../../utils/tool';

class Widgets extends Component {
    componentWillMount(){
        this.isMoving = false;
        this.height_moving = false;
        this.scrollMoving = false;
        this.startPosition = {
            x: 0,
            y: 0
        };
        this.movingPosition = {
            x: 0,
            y: 0
        };
    }
    componentDidMount(){
        this.initElements();
        this.bindEvent();
        
        let headerId = "usedWidgetsTimelineHeader";
        let timelineTool = this.state.timelineTool;
        this.maxHeight = this.elements.creatorEditor.height();
        this.handleOnSortable(this.elements.usedwidgetContainer,"y");

        this.createTimeline({
            holderId: headerId,
            totalLength: timelineTool.width,
            totalLeft: timelineTool.left * timelineTool.scale / 100
        });
        this.updateScroll();
        this.elements.zoomCircle.css({
            left: (timelineTool.scale - 100) + "%"
        });
    }
    constructor(props) {
        super(props);
        this.state = {             
            has_red_packet: false,
            open_event_list: false,
            timelineTool: {
                scale: 100,
                width: 1370,
                left: 0,
                viewWidth: 1000
            },
            is_only_red: false,
        };
    }
    getInitialState() {
        this.state = {
            has_red_packet: has_red_packet,
            open_event_list: false,
            timelineTool: {
                scale: 100,
                width: 1370,
                left: 0,
                viewWidth: 1000
            },
            is_only_red: false,
        };
    }
    initElements(){
        this.elements = {
            editor: $(this.refs.editorLeft),
            timelineHeader: $(this.refs.timelineHeader),
            zoomCircle: $(this.refs.zoomCircle),
            timelineScroll: $(this.refs.timelineScroll),
            scrollBlock: $(this.refs.scrollBlock),
            timelineContainer: $(this.refs.timelineContainer),
            usedwidgetContainer: $(this.refs.usedwidgetContainer),
            creatorUsedWidgets: $(this.refs.creatorUsedWidgets),
            usedWidgetsHeader: $(this.refs.usedWidgetsHeader),
            creatorEditor: $(".creator-editor"),
            hiddenBtn: $(this.refs.hiddenBtn),
            standardButtons: $(this.refs.standardButtons),
            formHiddenBtn: $(this.refs.formHiddenBtn),
        };
    }
    bindEvent(){
        let self = this;
        function mouseDown(e){
            var x = e.clientX, y = e.clientY;

            self.startPosition.x = x;
            self.startPosition.y = y;
            self.isMoving = true;
        }
        function mouseMove(e){
            if (self.isMoving){
                var x = e.clientX, y = e.clientY;
                self.movingPosition.x = x;
                self.movingPosition.y = y;

                self.updateScale(self.startPosition, self.movingPosition);

                self.startPosition.x = x;
                self.startPosition.y = y;

                self.updateScroll();
                self.updateTimeline();
            }
        }
        function mouseUp(e){
            if (self.isMoving){
                self.isMoving = false;

                var x = e.clientX, y = e.clientY;

                self.movingPosition.x = x;
                self.movingPosition.y = y;

                self.updateScale(self.startPosition, self.movingPosition);
            }
        }

        this.elements.zoomCircle.mousedown(mouseDown);
        this.elements.zoomCircle.mousemove(mouseMove);
        this.elements.zoomCircle.mouseup(mouseUp);
        window.addEventListener("mousemove",mouseMove);
        window.addEventListener("mouseup",mouseUp);

        function ScrollmouseDown(e){
            var x = e.clientX,y = e.clientY;
            self.startPosition.x = x;
            self.startPosition.y = y;
            self.scrollMoving = true;
        };
        function ScrollmouseMove(e){
          if(self.scrollMoving){
                var x = e.clientX,y = e.clientY;
                self.movingPosition.x = x;
                self.movingPosition.y = y;
                self.ScrollupdateScale(self.startPosition,self.movingPosition);
                self.startPosition.x = x;
                self.startPosition.y = y;
            }
        };
        function ScrollmouseUp(e){
             if(self.scrollMoving){
                self.scrollMoving = false;
                var x = e.clientX,y = e.clientY;
                self.movingPosition.x = x;
                self.movingPosition.y = y;
                self.ScrollupdateScale(self.startPosition,self.movingPosition);
            }
        };
        self.elements.scrollBlock.mousedown(ScrollmouseDown);
        self.elements.scrollBlock.mousemove(ScrollmouseMove);
        self.elements.scrollBlock.mouseup(ScrollmouseUp);

        window.addEventListener("mousemove",ScrollmouseMove);
        window.addEventListener("mouseup",ScrollmouseUp);

        function creato_mouseDown(e){
            var x = e.clientX,y = e.clientY;
            self.startPosition.x = x;
            self.startPosition.y = y;
            self.height_moving = true;
        }
        function creato_mouseMove(e){
            if(self.height_moving){
                var x = e.clientX,y = e.clientY;
                self.movingPosition.x = x;
                self.movingPosition.y = y;
                self.updateHeight(self.startPosition,self.movingPosition);
                self.startPosition.x = x;
                self.startPosition.y = y;
            }
        }
        function creato_mouseUp(e){
            if(self.height_moving){
                self.height_moving = false;
                var x = e.clientX,y = e.clientY;
                self.movingPosition.x = x;
                self.movingPosition.y = y;
                self.updateHeight(self.startPosition,self.movingPosition);
            }
        }
        this.elements.timelineHeader.mousedown(creato_mouseDown);
        this.elements.timelineHeader.mousemove(creato_mouseMove);
        this.elements.timelineHeader.mouseup(creato_mouseUp);
        this.elements.usedWidgetsHeader.mousedown(creato_mouseDown);
        this.elements.usedWidgetsHeader.mousemove(creato_mouseMove);
        this.elements.usedWidgetsHeader.mouseup(creato_mouseUp);
        window.addEventListener("mousemove",creato_mouseMove);
        window.addEventListener("mouseup",creato_mouseUp);
//        window.addEventListener('resize',self.updateScroll);
//        var timer;
//        function toggleHiddenBtn(){
//            clearTimeout(timer);
//            var root = self.props.root;
//            root.setState({showStandardBtns: true});
//        }
//        function hideHiddenBtn(){
//            var root = self.props.root;
//            timer = setTimeout(function(){
//                root.setState({showStandardBtns: false});
//            },1000)
//        }
//        this.elements.hiddenBtn.mouseover(toggleHiddenBtn);
//        this.elements.hiddenBtn.mouseout(hideHiddenBtn);
    }
    handleOnSortable (element = {}, axis = "") {
      element.sortable({
          axis: axis,
          start: (e, ui)=> start(e, ui),
          update: (e, ui)=> update(e, ui),
      });
      let from, to;
      const start = (e, ui) => {
          from = ui.item.index();
      };
      const update = (e, ui) => {
          to = ui.item.index();
          this.reorder(from, to);
      };
    }
    reorder(from,to){
        const {widgets,selectedPageId,updateWidget} = this.props;
        let keys = [],
            nowWidgets = widgets;
        if (!nowWidgets.length) return;
        // anti-moth 1593 nowWidgets顺序与取得from和to值的列表顺序相反
    //        from = nowWidgets.length - 1 - from;
    //        to = nowWidgets.length - 1 - to;
        nowWidgets.splice(to, 0, nowWidgets.splice(from, 1)[0]);

        let newKeys =[], newWidgets = [];
        for(let i = nowWidgets.length-1; i >= 0; i--){
            newKeys.push(nowWidgets[i].id);
            newWidgets.push(nowWidgets[i]);
        }
        updateWidget({newWidgets})
    }
    reorderWidgets(){//widgets倒序排列
        const {widgets} = this.props;
        widgets.sort(tool.sortBy('sort',true,parseInt));
        return widgets;
    }
    updateScale(startPos, endPos){
        let timelineTool = this.state.timelineTool;
        let _x = endPos.x - startPos.x;

        timelineTool.scale = timelineTool.scale + _x;
        timelineTool.width = timelineTool.scale * 14.20;

        if (timelineTool.scale > 200){
            timelineTool.scale = 200;
        }

        if (timelineTool.scale < 100){
            timelineTool.scale = 100;
        }

        if (timelineTool.scale <= 200 && timelineTool.scale >= 100){
            this.elements.zoomCircle.css({
                left: (timelineTool.scale - 100) + "%"
            });
            timelineTool.left = 0 + "%";
        }
        this.setState({
            timelineTool: timelineTool
        });
    }
    ScrollupdateScale(startPos,endPos){
        let _x = endPos.x-startPos.x;
        let tool = this.state.timelineTool;
        let _left =this.elements.scrollBlock.position().left;
        let toolScrollWidth = this.elements.timelineScroll.width();
        let scrollBlockWidth =this.elements.scrollBlock.width();
         _left = _left + _x;
        tool.viewWidth = this.elements.creatorUsedWidgets.width();
        if(tool.width)
        if(_left>=toolScrollWidth-scrollBlockWidth || _left<=0){
            _left = _left - _x;
        }

        tool.left = _left*100/toolScrollWidth;

        this.elements.scrollBlock.css({"left":_left});
        this.updateTimeline();
    }
    updateHeight(startPos, endPos){
        let _y = endPos.y-startPos.y,_top;
        let top =this.elements.creatorUsedWidgets.height();
        _top = top -_y;
        if(_top<=210||_top>= this.maxHeight){
            _top =top+_y;
            return;
        }
        this.elements.creatorUsedWidgets.css('height',_top);
        this.elements.usedwidgetContainer.css('height',_top-30);
    }
    handleOnZoomChanged(type){
        const timelineTool = this.state.timelineTool;
        
        if (type == "sub"){
            if (timelineTool.scale >= 100){
                timelineTool.scale = timelineTool.scale - 1;
            }
        } else {
            if (timelineTool.scale <= 200){
                timelineTool.scale = timelineTool.scale + 1;
            }
        }
        timelineTool.width = timelineTool.scale * 14.20;
        this.elements.zoomCircle.css({
            left: (timelineTool.scale - 100) + "%"
        });
        this.setState({
            timelineTool: timelineTool
        });
        this.updateScroll();
        this.updateTimeline();
    }
    updateScroll(){
        let toolScrollWidth = this.elements.timelineScroll.width();
        let timelineTool = this.state.timelineTool;

        timelineTool.viewWidth = this.elements.timelineContainer.width();

        this.elements.scrollBlock.css({
            left: timelineTool.left + "%",
            width: timelineTool.viewWidth / timelineTool.width * toolScrollWidth
        });

        this.elements.timelineScroll.css({
            display: timelineTool.width < timelineTool.viewWidth ? "none" : "block"
        })
    }
    updateTimeline(){
        let timelineTool = this.state.timelineTool;
        let timelineHeader = this.elements.timelineHeader;
        this.createTimeline({
            holderId: "usedWidgetsTimelineHeader",
            totalLength: timelineTool.width,
            totalLeft: timelineTool.left * timelineTool.scale / 100
        });
    }
    createTimeline(opts){
        let options = {
            holderId: 'holder',
            timelineHeight: 30,
            totalLength: 1550,
            mainGradCount: 60,
            minorGradCount: 2,
            totalLeft: 0
        };
        options = $.extend(true, {}, options, opts);

        $("#" + options.holderId).html("");

        // 主刻度线步长
        options.mainGradLength = parseFloat((options.totalLength - 10) / options.mainGradCount);
        // 小刻度线步长
        options.minorGradLength = parseFloat(options.mainGradLength / options.minorGradCount);
        // 绘制画布 高度43px 宽度totalLength
        let r = Raphael(options.holderId, options.totalLength + 'px', "43px");
        // 主刻度线高度
        options.mainGradHeight = options.timelineHeight / 2;
        // 小刻度线高度
        options.minorGradHeight = options.mainGradHeight / 2;
        // 绘制刻度线横线的Path值
        let lhbPath = 'M0 ' + options.timelineHeight + 'L' + options.totalLength + ' ' +options.timelineHeight;
        // r.path(lhbPath);
        // 在Point(10,8)位置绘制0
        r.text(10, 8, 0);
        // 绘制文本、刻度线
        for (let i = 0; i < options.mainGradCount; i++) {
            let lvmainStartX = (i + 1) * options.mainGradLength;
            let lvmainStartY = options.timelineHeight;
            let lvmainEndX = lvmainStartX,
                lvmainEndY = options.timelineHeight - 10;
            let lvmainPath = 'M' + lvmainStartX + ' ' + lvmainStartY + 'L' + lvmainEndX + ' ' + lvmainEndY;

            r.path(lvmainPath);

            let tvmX = lvmainStartX - 1;
            let tvmY = options.timelineHeight;

            if ((i + 1) % 5 == 0) {
                r.text(tvmX, 8, i + 1);
            }
            // paint the minor grad
            for (let j = 0; j < options.minorGradCount - 1; j++) {
                let lvminorStartX = (j + 1) * options.minorGradLength + i * options.mainGradLength;
                let lvminorStartY = options.timelineHeight;

                let lvminorEndX = lvminorStartX,
                    lvminorEndY = options.timelineHeight - 5;
                let lvminorPath = 'M' + lvminorStartX + ' ' + lvminorStartY + 'L' + lvminorEndX + ' ' + lvminorEndY;

                r.path(lvminorPath);
            }
        }
        $("#" + options.holderId + " svg").css({left: -options.totalLeft + "%"});
        $(".widget-timelines-holder").css({left: -options.totalLeft + "%"});
    }
    handleOnToggleAllVisible(){
        const {toggleWidgetsVisible,widgets,widgetAllVisible} = this.props;

        let widgetIds = [];
        for(let i =0 ;i< widgets.length; i++){
            widgetIds.push(widgets[i].id);
        }
        //还未更新state.widgetAllVisible
        toggleWidgetsVisible(widgetIds,!this.getWidgetAllVisible(widgets))
    }
    getWidgetAllVisible(widgets) {
        for(let i =0 ;i< widgets.length; i++){
            if(widgets[i].visible===false) return false;
        }
        return true;
    }
    render (){
        const {showTimeline,showList,widgets: currentWidget,timelines, selectedTimeline,selectedTimelineId} = this.props;
        
        let widgets = this.reorderWidgets(currentWidget);
        var iconCheckedNode = "";
        const widgetAllVisible = this.getWidgetAllVisible(widgets)
        if (widgetAllVisible){
            iconCheckedNode = <div onClick={() => this.handleOnToggleAllVisible()} className="icon_eye-open"></div>
        } else {
            iconCheckedNode = <div onClick={() => this.handleOnToggleAllVisible()} className="icon_unchecked"></div>
        }
        var noWidgetNode = "";
        if (!widgets.length){
            noWidgetNode = <div className='if_no_timeline'>还没有素材可以编辑</div>
        }
        
    return (
        <div>
            <div ref='creatorUsedWidgets' style={{display:showList ? "block" : "none"}} className={"creator-panel creator-used-widgets " + (showTimeline ? "with-timeline" : "")}>
				<div className="used-widgets-header" ref='usedWidgetsHeader'>
					<div className="btn-visual">
						{iconCheckedNode}
					</div>
					<header className="panel-title">
						<span>素材列表</span>
						<span><img src="/static/idealsee/images/new_editor/editor/chufa_lv@1x.png" /></span>
					</header>
				</div>
				<div id="usedWidgetsTimelineHeader" ref="timelineHeader" style={{display:showTimeline ? "block" : "none"}} className="used-widgets-timeline-header" data-timeline-tool="timelineTool" data-timeline-header>
				</div>
				<div ref='usedwidgetContainer' className="used-widgets-container" style={{top:(showTimeline ? "-30px" : "0px"),width:"auto"}}>
					{
						widgets.map((widget,index)=>{
							return (
								<UsedWidget key={widget.id+index} timelines={timelines.filter(w => w.widget_id === widget.id)} widget={widget} showTimeline={showTimeline} selectedTimeline={selectedTimeline} timelineTool={this.state.timelineTool} selectedTimelineId={selectedTimelineId}/>
							)
						})
					}
					{noWidgetNode}
				</div>
				<div className="used-timeline-tool" style={{display:showTimeline ? "block" : "none"}}>
					<figure ref="timelineContainer" className="timeline-tool-container">
						<div className="timeline-tool-zoom">
							<div data-type="sub" onClick={() => this.handleOnZoomChanged("sub")} className="zoom-xiao">
								<span></span>
							</div>
							<div className="zoom-container">
								<div className="zoom-bar"></div>
								<div ref="zoomCircle" className="zoom-circle"></div>
							</div>
							<div data-type="add" onClick={() => this.handleOnZoomChanged('add')} className="zoom-da">
								<span></span>
							</div>
						</div>
						<div ref="timelineScroll" className="timeline-tool-scroll">
							<div ref="scrollBlock" className="scroll-block"></div>
						</div>
					</figure>
				</div>
			</div>
        </div>
        )
    }
}

const mapStateToProps = ({ editor, widgets, timelines }) => {
  const pageId = editor.selectedPageId;
  return {
      showTimeline: editor.showTimeline,
      showList: editor.showList,
      has_red_packet: editor.has_red_packet,
      selectedTimelineId: editor.selectedTimelineId,
      selectedPageId: editor.selectedPageId,
      updateWidget: editor.updateWidget,
      toggleWidgetsVisible: editor.toggleWidgetsVisible,
      widgets: widgets.filter(w => w.page_id === pageId && !w.delFlag),
      timelines: timelines.filter(t => t.page_id === pageId && !t.delFlag)
  };
};

const mapDispatchToProps = (dispatch) => {
  return bindActionCreators(widgetsActions, dispatch);
};


export default connect(mapStateToProps, mapDispatchToProps)(Widgets);